package com.ronri.ams.sample;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.CustomDialog;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.DictBean;
import com.ronri.ams.bean.SamplingBean;
import com.ronri.ams.bean.sample_info;
import com.ronri.choosephotos.PhotoItem;
import com.ronri.common.DateUtil;
import com.ronri.common.StringManager;
import com.ronri.common.UrlEncode;
import com.ronri.db.RemoteDataService;
import com.ronri.list.editview.AbstractItemElement;
import com.ronri.list.editview.DefaultItemElement;
import com.ronri.list.editview.ExtendListEditAdapter;
import com.ronri.list.editview.ListEditAdapter;
import com.ronri.list.editview.PhotoItemElement;
import com.ronri.list.editview.controls.EditCardTextBox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


public class activity_form_sample extends abstract_activity {

    private List<AbstractItemElement> mItems = new ArrayList<AbstractItemElement>();

    private ExtendListEditAdapter mAdapter;

    private SamplingBean mSample = null;

    private boolean mbChange = false;

    private String mSectionDict = "";

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String szJson = "";
        setContentView(R.layout.activity_sample_edit);
        Log.i("aaa","activity_form_sample");
        mContext = this;

        Bundle bundle = getIntent().getExtras();

        mSectionDict = bundle.getString("dict");

        ExpandableListView listView = (ExpandableListView) findViewById(R.id.list_edit);

        //
        setTitle("样品抽样编辑", "确定");

        //
        init();

        // 隐藏系统箭头
        listView.setGroupIndicator(null);

        // 创建Demo
        CreateDemo();

        mAdapter = new ExtendListEditAdapter(this, mItems, new ListEditAdapter.Callback() {
            @Override
            public void click(View v) {

            }
        });


        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getBaseContext(), "Children Click", Toast.LENGTH_LONG);
            }
        });

        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                switch (groupPosition) {
                    case 0: {   // 抽样机构
                    }
                    break;
//                    case 1:{
//                        Intent intent = new Intent(getApplicationContext(), activity_region_select.class);
//                        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_AREA);
//                    }
//                    break;
                    case 1: {   // 抽样人员
                        Intent intent = new Intent(getApplicationContext(), activity_mutil_select_humen.class);
                        Bundle bundle = new Bundle();
                        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                                InitApplication.SystemConfig.getModule().getHumen().getAddress());
                        /*** 设置远程地址 ***/
                        bundle.putString("remoteAddress", szRemoteAddress);
                        //bundle.putString("data", "[{\"humen_id\":1, \"humen_name\":\"吴冬梅\", \"humen_type\":1},{\"humen_id\":1, \"humen_name\":\"吴建敏\", \"humen_type\":1},{\"humen_id\":1, \"humen_name\":\"李昙云\", \"humen_type\":2},{\"humen_id\":1, \"humen_name\":\"储力先\", \"humen_type\":2}]");
                        bundle.putString("filterKeyName", "name");
                        bundle.putString("viewTitleName", "name");
                        bundle.putInt("control_id", groupPosition);
                        bundle.putInt("selectMode", ListView.CHOICE_MODE_SINGLE);
                        bundle.putString("title", "抽样人员");
                        bundle.putString("vtitle", "添加");
                        bundle.putString("vid", gSampleInfo.getSample_user());
                        bundle.putString("value", gSampleInfo.getUser_name());

                        intent.putExtras(bundle);

                        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_HUMEN);
                    }
                    break;
                    case 2: {   // 监测环节
                       getSectionData(groupPosition);
                    }
                    break;
                    case 3: {   // 受检对象
                        Intent intent = new Intent(getApplicationContext(), activity_control_map_select.class);
                        Bundle bundle = new Bundle();

                        /*** 设置远程地址 ***/
                        bundle.putString("remoteAddress", getResources().getString(R.string.remote_get_sample_worker));
                        bundle.putString("filterKeyName", "breed_name");
                        bundle.putString("viewTitleName", "breed_name");
                        bundle.putInt("control_id", groupPosition);
                        bundle.putString("title", "受检对象");
                        bundle.putString("vtitle", "常规检索");
                        bundle.putInt("vid", gSampleInfo.getInspectd_unit());
                        bundle.putString("value", gSampleInfo.getInspectd_name());
                        intent.putExtras(bundle);

                        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_ENT);
                    }
                    break;
                    case 4: {   // 样品信息
                        if (gSampleInfo.getInspectd_name() == null) {
                                CustomDialog.Builder builder = new CustomDialog.Builder(activity_form_sample.this);
                                builder.setMessage("请选择受检企业。");
                                builder.setTitle("信息提示");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                                builder.create().show();
                                break;
                        }else {
                            if (gSampleInfo.getInspectd_name().isEmpty()) {
                                CustomDialog.Builder builder = new CustomDialog.Builder(activity_form_sample.this);
                                builder.setMessage("请选择受检企业。");
                                builder.setTitle("信息提示");

                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                                builder.create().show();
                                break;
                            }
                        }

                        Intent intent = new Intent(getApplicationContext(), activity_sample_list.class);
                        Bundle bundle = new Bundle();

                        /*** 设置远程地址 ***/
                        bundle.putString("remoteAddress", getResources().getString(R.string.remote_get_sample_worker));
                        bundle.putString("filterKeyName", "breed_name");
                        bundle.putString("viewTitleName", "breed_name");
                        bundle.putString("data", "");
                        bundle.putInt("control_id", groupPosition);
                        bundle.putString("title", "样品信息");
                        bundle.putString("vtitle", "添加样品");

                        intent.putExtras(bundle);

                        startActivityForResult(intent, SystemEnvironmental.Sample_MAIN);
                    }
                    break;
                    case 5: {   // 抽样拍照
                        Intent intent = new Intent(getApplicationContext(), activity_photograph.class);
                        Bundle bundle = new Bundle();

                        /*** 设置远程地址 ***/
                        bundle.putInt("control_id", groupPosition);
                        bundle.putString("title", "抽样拍照");
                        bundle.putString("vtitle", "确定");
                        bundle.putString("data", JSON.toJSONString(((PhotoItemElement)mItems.get(5)).GetPhotos()));

                        intent.putExtras(bundle);

                        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_PHOTO);
                    }
                    break;
                    case 6: {   // 受检者签名
                        Intent intent = new Intent(getApplicationContext(), activity_control_sign.class);
                        Bundle bundle = new Bundle();

                        /*** 设置远程地址 ***/
                        bundle.putInt("edit_layout", R.layout.control_edit_box_with_locate);
                        bundle.putInt("control_id", groupPosition);
                        bundle.putString("title", "受检者签名");
                        bundle.putString("vtitle", "确定");

                        if (gSampleInfo.getSample_sign().size() > 0)
                            bundle.putString("filename", gSampleInfo.getSample_sign().get(0).getAttach_name());

                        intent.putExtras(bundle);

                        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_SIGN);
                    }
                    break;
                }

                return false;
            }
        });

        /****
         * 列表Item点击事件
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getBaseContext(), "setOnItemClickListener Click", Toast.LENGTH_LONG);
            }
        });
    }

    /***
     * 接收弹出框输入的结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            mbChange = true;
            switch (requestCode) {
                case SystemEnvironmental.Sample_INPUT_DEPT:{
                    Bundle bundle =  data.getExtras();
                    String szResult = bundle.getString("returnValue");

                    if(szResult != null) {
                        JSONArray jsonArray = JSON.parseArray(szResult);
                        if(jsonArray != null) {
                            JSONObject obj = (JSONObject) jsonArray.get(0);
                            if(obj.containsKey("dept_name")){
                                String ss = obj.getString("dept_name");
                                mItems.get(0).setInfo(ss);
                                mAdapter.notifyDataSetChanged();
                                mSample.setdept(ss);
                            }
                        }
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_AREA:{
                    //if (!StringManager.isEmpty(gSampleInfo.getUser_name())) {
                        Bundle bundle =  data.getExtras();
                        String szName = bundle.getString("region_name");
                        String szCode = bundle.getString("region_code");
                        gSampleInfo.setArea_name(szName);
                        gSampleInfo.setSample_area(szCode);

                        mItems.get(1).setInfo(gSampleInfo.getArea_name().replace(",", "\r\n"));
                        mAdapter.notifyDataSetChanged();
                    //}
                }
                break;
                case SystemEnvironmental.Sample_INPUT_HUMEN:{
                    if (!StringManager.isEmpty(gSampleInfo.getUser_name())) {
                        mItems.get(1).setInfo(gSampleInfo.getUser_name().replace(",", "\r\n"));
                        mAdapter.notifyDataSetChanged();
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_NATURE:{
                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("returnValue");
                    if(szResult != null) {
                        JSONArray jsonArray = JSON.parseArray(szResult);
                        if(jsonArray != null) {
                            JSONObject obj = (JSONObject) jsonArray.get(0);
                            if(obj.containsKey("section_name")){
                                String ss = obj.getString("section_name");
                                String sa = obj.getString("section_id");
                                gSampleInfo.setSection(sa);
                                gSampleInfo.setSection_name(ss);
                                mItems.get(2).setInfo(ss);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_ENT:{
                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("title");
                    int nId = bundle.getInt("id");
                    if (szResult != "") {
                        mItems.get(3).setInfo(szResult);
                        gSampleInfo.setInspectd_name(szResult);
                        gSampleInfo.setInspectd_unit(nId);

                        mAdapter.notifyDataSetChanged();
                        mSample.setEnt(szResult);
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_Samples:{

                    if(gSampleInfo.getInspectd_name().isEmpty()){
                        CustomDialog.Builder builder = new CustomDialog.Builder(this);
                        builder.setMessage("请选择受检对象");
                        builder.setTitle("信息提示");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                        builder.create().show();
                        break;
                    }

                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("returnValue");
                    if (szResult != "") {
                        List<PhotoItem> lItem = JSONArray.parseArray(szResult, PhotoItem.class);
                        ((PhotoItemElement) mItems.get(4)).SetPhotos(lItem);

                        mAdapter.notifyDataSetChanged();
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_PHOTO: {
                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("returnValue");
                    if (szResult != "") {
                        List<PhotoItem> lItem = JSONArray.parseArray(szResult, PhotoItem.class);


                        ((PhotoItemElement) mItems.get(5)).SetPhotos(lItem);

                        List<sample_info.SampleAttachBean> lPhoto = new ArrayList<>();

                        for(PhotoItem item : lItem){
                            sample_info.SampleAttachBean bean = new sample_info.SampleAttachBean();
                            bean.setAttach_name(item.PhotoPath);
                            bean.setRemark(item.getMemo());
                            bean.setLocation(item.getAddress());
                            bean.setLatitude(String.valueOf(item.getLatitude()));
                            bean.setLongitude(String.valueOf(item.getLongitude()));
                            bean.setCreate_user(InitApplication.LoginInfo.getData().getUser_id());
                            bean.setAttach_url(item.getUrl());
                            bean.setUpload_date(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));

                            lPhoto.add(bean);
                        }

                        gSampleInfo.setSample_attach(lPhoto);

                        // mSample.setPhotos(lItem);
                        mAdapter.notifyDataSetChanged();
                    }
                }
                break;
                case SystemEnvironmental.Sample_INPUT_SIGN: {
                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("returnValue");
                    if (szResult != "") {
                        List<PhotoItem> lItem = JSONArray.parseArray(szResult, PhotoItem.class);

                        ((PhotoItemElement) mItems.get(6)).SetPhotos(lItem);

                        mAdapter.notifyDataSetChanged();

                        if (lItem.size() > 0) {
                            List<sample_info.SampleSignBean> lsign = new ArrayList<>();
                            sample_info.SampleSignBean sign = new sample_info.SampleSignBean();
                            PhotoItem item = lItem.get(0);

                            sign.setAttach_name(item.PhotoPath);
                            sign.setAttach_url(item.getUrl());
                            sign.setLatitude(String.valueOf(item.getLatitude()));
                            sign.setLongitude(String.valueOf(item.getLongitude()));
                            sign.setCreate_user(InitApplication.LoginInfo.getData().getUser_id());
                            sign.setLocation(item.getAddress());
                            sign.setUpload_date(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));

                            lsign.add(sign);

                            gSampleInfo.setSample_sign(lsign);

                            mSample.setSign(lItem.get(0).getPhotoPath());
                        }
                    }
                }
                break;
                case SystemEnvironmental.Sample_MAIN:{

                    mItems.get(4).setInfo(gSampleInfo.GetSamplebreed());
                    mAdapter.notifyDataSetChanged();
                    /*
                    Bundle bundle = data.getExtras();

                    String szResult = bundle.getString("returnValue");
                    if (szResult != "") {
                        String szSample = "";
                        String szSplit = "";

                        List<SampleBean> lItem = JSONArray.parseArray(szResult, SampleBean.class);
                        for(SampleBean ii : lItem){
                            szSample = szSample + szSplit + ii.getName();
                            szSplit = ",";
                        }

                        if (mSample != null){
                            mSample.setSamples(lItem);
                        }
                        mItems.get(4).setInfo(szSample);
                        mAdapter.notifyDataSetChanged();
                    }*/
                }
            }
        }
    }

    /****
     * 创建DEMO
     */
    private void CreateDemo() {
        if (mSample == null)
            mSample = new SamplingBean();

        AbstractItemElement iTems = new DefaultItemElement(this,
                "抽样机构",
                gSampleInfo.getDetector_name(),
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心", false, new EditCardTextBox());

        mItems.add(iTems);

//        iTems = new DefaultItemElement(this,
//                "监测区域",
//                gSampleInfo.getArea_name(),
//                null,
//                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
//                "fRegion",
//                "", false, new EditCardTextBox());
//
//        mItems.add(iTems);

        String szHumen = gSampleInfo.getUser_name();

        if (StringManager.isEmpty(szHumen))
            szHumen = "";

        iTems = new DefaultItemElement(this,
                "抽样人员",
                StringManager.InitString(gSampleInfo.getUser_name()).replace(",", "\r\n"),
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心", false, new EditCardTextBox());

        mItems.add(iTems);

        iTems = new DefaultItemElement(this,
                "监测环节",
                gSampleInfo.getSection_name(),
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心", false, new EditCardTextBox());

        mItems.add(iTems);

        iTems = new DefaultItemElement(this,
                "受检对象",
                gSampleInfo.getInspectd_name(),
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心", false, new EditCardTextBox());

        mItems.add(iTems);

        iTems = new DefaultItemElement(this,
                "样品信息",
                gSampleInfo.GetSamplebreed(),
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心", false, new EditCardTextBox());

        mItems.add(iTems);

        {
            iTems = new PhotoItemElement(this,
                "抽样拍照",
                "",
                null,
                getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                "fRegion",
                "常州市农畜水产品质量监督检验测试中心",
                false);


            List<PhotoItem> lPhoto = new ArrayList<PhotoItem>();

            for (sample_info.SampleAttachBean ii : gSampleInfo.getSample_attach()) {

                PhotoItem photoItem = new PhotoItem();

                photoItem.PhotoPath = ii.getAttach_name();

                photoItem.setUrl(ii.getAttach_url());
                photoItem.setAddress(ii.getLocation());
                photoItem.setLatitude(Double.valueOf(ii.getLatitude()));
                photoItem.setLongitude(Double.valueOf(ii.getLongitude()));
                photoItem.setMemo(ii.getRemark());

                lPhoto.add(photoItem);
            }

            ((PhotoItemElement) iTems).SetPhotos(lPhoto);

            mItems.add(iTems);
        }

        {
            iTems = new PhotoItemElement(this,
                    "受检者签名",
                    "",
                    null,
                    getResources().getDrawable(R.drawable.jiandujiancha_icon_more),
                    "fRegion",
                    "常州市农畜水产品质量监督检验测试中心",
                    false);
            List<PhotoItem> lPhoto = new ArrayList<PhotoItem>();

            for (sample_info.SampleSignBean ii : gSampleInfo.getSample_sign()) {
                PhotoItem photoItem = new PhotoItem();
                photoItem.PhotoPath = ii.getAttach_name();
                photoItem.setUrl(ii.getAttach_url());
                photoItem.setAddress(ii.getLocation());
                photoItem.setLatitude(Double.valueOf(ii.getLatitude()));
                photoItem.setLongitude(Double.valueOf(ii.getLongitude()));

                lPhoto.add(photoItem);
                break;
            }

            ((PhotoItemElement) iTems).SetPhotos(lPhoto);

            mItems.add(iTems);
        }

    }

    /**
     * 确认反回
     * @return
     */
    @Override
    public boolean SureReturn() {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();

        bundle.putString("returnValue", JSON.toJSONString(mSample));
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);

        return super.SureReturn();
    }

    @Override
    public boolean CancelReturn() {

        if (mbChange == true){
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
            builder.setMessage("已修改当前采样记录，是否保存？");
            builder.setTitle("信息提示");
            builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();

                    bundle.putString("returnValue", JSON.toJSONString(mSample));
                    intent.putExtras(bundle);

                    setResult(RESULT_OK, intent);
                    SureReturn();
                }
            });

            builder.setNegativeButton("放弃",  new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    toFinish();
                }
            });

            builder.create().show();

            return false;
        }else {
            return super.CancelReturn();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //尝试GC，尽可能释放内存。
        System.gc();
    }

    /****
     * 获取远程数据
     */
    public void getSectionData(final int groupPosition) {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = "http://120.55.93.238:8080/ams//api/dict.json";

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("code", "section");
            mParam.put("num", "");

        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {

                    @Override
                    public void OnResultEvent(String szString) {
                        DictBean bean= JSON.parseObject(szString, DictBean.class);
                        String szSplit = "";
                        String szSec="";
                        if(bean.isSuccess()){
                            for(int i=0;i<bean.getData().size();i++){
                                String name=bean.getData().get(i).getName();
                                String num=bean.getData().get(i).getNum();

                                szSec += szSplit + "{\"section_name\":\"" + name + "\",\"section_id\":" + num + "}";
                                szSplit = ",";
                            }

                            szSec = "[" + szSec + "]";

                            Intent intent = new Intent(getApplicationContext(), activity_control_select.class);
                            Bundle bundle = new Bundle();

                            /*** 设置远程地址 ***/
                            bundle.putString("remoteAddress", getResources().getString(R.string.remote_get_sample_nature));
                            bundle.putString("data", szSec);
                            bundle.putString("filterKeyName", "section_id");
                            bundle.putString("viewTitleName", "section_name");
                            bundle.putInt("control_id", groupPosition);
                            bundle.putInt("selectMode", ListView.CHOICE_MODE_SINGLE);
                            bundle.putString("title", "监测环节");
                            bundle.putString("vtitle", "确定");
                            bundle.putString("value", gSampleInfo.getSection());
                            intent.putExtras(bundle);

                            startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_NATURE);
                        }
                    }

                    @Override
                    public void OnRuningState(int nStatus) {

                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                });
    }
}
